package com.investment.advisor.repository;

import com.investment.advisor.entity.LoginRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.Lock;
import javax.persistence.LockModeType;

import java.util.List;
import java.util.Optional;

public interface LoginRecordRepository extends JpaRepository<LoginRecord, Long> {
    
    @Query("SELECT lr FROM LoginRecord lr WHERE lr.logoutTime IS NULL AND lr.loginStatus = 'ONLINE'")
    List<LoginRecord> findOnlineUsers();

    @Query("SELECT COUNT(lr) FROM LoginRecord lr WHERE lr.logoutTime IS NULL AND lr.loginStatus = 'ONLINE'")
    long countOnlineUsers();

    LoginRecord findTopByUserIdOrderByLoginTimeDesc(Long userId);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT lr FROM LoginRecord lr WHERE lr.userId = ?1 AND lr.logoutTime IS NULL AND lr.loginStatus = 'ONLINE'")
    Optional<LoginRecord> findActiveLoginRecordForUpdate(Long userId);
} 